package chan.project.controller;

import chan.project.common.BaseResponse;
import chan.project.common.ErrorCode;
import chan.project.common.ResultUtils;
import chan.project.exception.BusinessException;
import chan.project.model.dto.travelPlanThumb.TravelPlanThumbAddRequest;
import chan.project.model.entity.TravelPlanThumb;
import chan.project.model.entity.User;
import chan.project.service.TravelPlanThumbService;
import chan.project.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 旅行计划点赞接口
 *
 * @author <a href="https://github.com/kavansp">kavansp</a>
 *
 */
@RestController
@RequestMapping("/travelPlanThumb")
@Slf4j
public class TravelPlanThumbController {

    @Resource
    private TravelPlanThumbService travelPlanThumbService;

    @Resource
    private UserService userService;

    /**
     * 点赞 / 取消点赞
     *
     * @param travelPlanThumbAddRequest
     * @param request
     * @return resultNum 本次点赞变化数
     */
    @PostMapping("/")
    public BaseResponse<Integer> doThumb(@RequestBody TravelPlanThumbAddRequest travelPlanThumbAddRequest,
                                         HttpServletRequest request) {
        if (travelPlanThumbAddRequest == null || travelPlanThumbAddRequest.getTravelPlanId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 登录才能点赞
        final User loginUser = userService.getLoginUser(request);
        long travelPlanId = travelPlanThumbAddRequest.getTravelPlanId();
        int result = travelPlanThumbService.doTravelPlanThumb(travelPlanId, loginUser);
        return ResultUtils.success(result);
    }

    /**
     * 检查是否已经点赞
     * @param travelPlanId
     * @param request
     * @return
     */
    @GetMapping
    public BaseResponse<Boolean> isThumb(long travelPlanId,HttpServletRequest request){
        if(travelPlanId <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        final User loginUser = userService.getLoginUser(request);
        LambdaQueryWrapper<TravelPlanThumb> travelPlanThumbLambdaQueryWrapper = new LambdaQueryWrapper<>();
        travelPlanThumbLambdaQueryWrapper.eq(TravelPlanThumb::getTravelPlanId,travelPlanId)
                        .eq(TravelPlanThumb::getUserId,loginUser.getId());
        TravelPlanThumb travelPlanThumb = travelPlanThumbService.getOne(travelPlanThumbLambdaQueryWrapper);
        return ResultUtils.success(travelPlanThumb != null);
    }
    // endregion
}
